package api

import (
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"itachi/models"
	"itachi/pkg/e"
	"itachi/pkg/util"
	"log"
	"net/http"
)

type auth struct {
	Username string `valid:"Required";MaxSize(50)`
	Password string `valid:"Required";MaxSize(50)`
}

func GetAuth(context *gin.Context) {
	username := context.Query("username")
	password := context.Query("password")
	valid := validation.Validation{}

	a := auth{Username: username, Password: password}
	flag, _ := valid.Valid(&a)

	data := make(map[string]interface{})

	code := e.INVALID_PARAMS

	if flag {
		isExist := models.CheckAuth(username, password)
		if isExist {
			token, err := util.GenerateToken(username, password)
			if err != nil {
				code = e.ERROR_AUTH_TOKEN
			} else {
				data["token"] = token
				code = e.SUCCESS
			}
		}
	} else {
		for _, v := range valid.Errors {
			log.Println(v.Key, v.Message)
		}
	}
	context.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}
